/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package model

import (
	"errors"
	"strings"
	"time"
	"gitee.com/tugoer/orivil/bundles/db"
)

var (
	ErrRecordExist = errors.New("record already exist")
)

type Channel struct {
	ID int
	Name string `gorm:"unique_index"`
	OpenSelect bool `gorm:"index"`
	CreatedAt *time.Time
}

func (c *Channel)Create() error {
	err := db.Gorm.Create(c).Error
	if err != nil {
		if strings.Contains(err.Error(), "uix_") {
			return ErrRecordExist
		}
	}
	return err
}

func (c *Channel)Update() error {
	var openSelect int
	if c.OpenSelect {
		openSelect = 1
	}
	return db.Gorm.Model(Channel{}).Where("id=?", c.ID).Updates(map[string]interface{}{
		"name": c.Name,
		"open_select": openSelect,
	}).Error
}

func (c *Channel)Delete() error {
	return db.Gorm.Delete(c).Error
}

// 查询所有可以选择的频道
func GetSelectChannels() (cs []*Channel, err error) {
	err = db.Gorm.Model(&Channel{}).Where("open_select=?", true).Find(&cs).Error
	return
}

func CountChannels() (total int) {
	db.Gorm.Model(&Channel{}).Count(&total)
	return
}

func QueryChannels(desc bool, limit, offset int) (cs []*Channel, err error) {
	order := "id asc"
	if desc {
		order = "id desc"
	}
	err = db.Gorm.Model(&Channel{}).Order(order).Limit(limit).Offset(offset).Find(&cs).Error
	return
}

func CloseSelects(ids []int) error {
	return db.Gorm.Model(&Channel{}).Where("id in (?)", ids).Update("open_select", false).Error
}

func GetChannel(id int) (c *Channel, err error) {
	c = &Channel{ID: id}
	err = db.Gorm.First(c).Error
	return
}
